﻿$(document).ready(function () {
    $("form").delegate(".component", "mousedown", function (md) {
    $(".popover").hide();

    md.preventDefault();
    var tops,
        mouseX = md.pageX,
        mouseY = md.pageY,
        $temp,
        timeout,
        $this = $(this),        
        delays = {
          main: 0,
          form: 120
        },
        type;

    if($this.parent().parent().parent().parent().attr("id") === "components"){
      type = "main";
    } else {
      type = "form";
    }

    var delayed = setTimeout(function(){
      if(type === "main"){
        $temp = $("<form class='form-horizontal col-md-6' id='temp'>").append($this.clone());
      } else {
        if($this.attr("id") !== "legend"){
          $temp = $("<form class='form-horizontal col-md-6' id='temp'>").append($this);
        }
      }

      $("body").append($temp);

      $temp.css({"position" : "absolute",
                 "top"      : mouseY - ($temp.height()/1) + "px",
                 "left"     : mouseX - ($temp.width()/1) + "px",
                 "opacity"  : "0.6"}).show()

      var half_box_height = ($temp.height()/2),
          half_box_width = ($temp.width()/2),
          $target = $("#target"),
          tar_pos = $target.position(),
          $target_component = $("#target .component");

      $(document).delegate("body", "mousemove", function(mm){

        var mm_mouseX = mm.pageX,
            mm_mouseY = mm.pageY;

        $temp.css({"top"      : mm_mouseY - half_box_height + "px",
          "left"      : mm_mouseX - half_box_width  + "px"});

        if ( mm_mouseX > tar_pos.left &&
          mm_mouseX < tar_pos.left + $target.width() + $temp.width()/2 &&
          mm_mouseY > tar_pos.top &&
          mm_mouseY < tar_pos.top + $target.height() + $temp.height()/2
          ){
            $("#target").css("background-color", "#fafafa");
            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
            tops = $.grep($target_component, function(e){
              return ($(e).position().top -  mm_mouseY + half_box_height > 0 && $(e).attr("id") !== "legend");
            });
            if (tops.length > 0){
              $(tops[0]).css("border-top", "2px solid #f00");
            } else{
              if($target_component.length > 0){
                $($target_component[$target_component.length - 1]).css("border-bottom", "2px solid #f00");
              }
            }
          } else{
            $("#target").css("background-color", "#fff");
            $target_component.css({"border-top" : "1px solid white", "border-bottom" : "none"});
            $target.css("background-color", "#fff");
          }
      });

      $("body").delegate("#temp", "mouseup", function(mu){
        mu.preventDefault();

        var mu_mouseX = mu.pageX,
            mu_mouseY = mu.pageY,
            tar_pos = $target.position();

        $("#target .component").css({"border-top" : "1px solid white", "border-bottom" : "none"});

        // acting only if mouse is in right place
        if (mu_mouseX + half_box_width > tar_pos.left &&
          mu_mouseX - half_box_width < tar_pos.left + $target.width() &&
          mu_mouseY + half_box_height > tar_pos.top &&
          mu_mouseY - half_box_height < tar_pos.top + $target.height()
          ){
            $temp.attr("style", null);
            // where to add
            if(tops.length > 0){
              $($temp.html()).insertBefore(tops[0]);
            } else {
              $("#target fieldset").append($temp.html());
            }
          } else {
            // no add
            $("#target .component").css({"border-top" : "1px solid white", "border-bottom" : "none"});
            tops = [];
          }

        //clean up & add popover
        $target.css("background-color", "#fff");
        $(document).undelegate("body", "mousemove");
        $("body").undelegate("#temp","mouseup");
        $("#target .component").popover({trigger: "manual"});
        $temp.remove();
        genSource();
      });
    }, delays[type]);

    $(document).mouseup(function () {
      clearInterval(delayed);
      return false;
    });
    $(this).mouseout(function () {
      clearInterval(delayed);
      return false;
    });
  });

  var genSource = function(){
    var $temptxt = $("<div>").html($("#build").html());
    //scrubbbbbbb
    $($temptxt).find(".component").attr({"title": null,
      "data-original-title":null,
      "data-type": null,
      "data-content": null,
      "rel": null,
      "trigger":null,
      "style": null});
    $($temptxt).find(".valtype").attr("data-valtype", null).removeClass("valtype");
    $($temptxt).find(".component").removeClass("component");
    $($temptxt).find("form").attr({"id":  null, "style": null});
    $("#source").val($temptxt.html().replace(/\n\ \ \ \ \ \ \ \ \ \ \ \ /g,"\n"));
  }

  //activate legend popover
  $("#target .component").popover({trigger: "manual"});
  //Mặc định >> Tool 
  $("#target").delegate(".component", "click", function(e){
    e.preventDefault();
    $(".popover").hide();
    var $active_component = $(this);
    $active_component.popover("show");
    var valtypes = $active_component.find(".valtype");
    $.each(valtypes, function (i, e) {
        var valID = "#" + $(e).attr("data-valtype");
      var val;
      if(valID ==="#placeholder"){
        val = $(e).attr("placeholder");
        $(".popover " + valID).val(val);
      } else if (valID === "#checkbox") {
          val = $(e).attr("checked");
          $(".popover " + valID).attr("checked", val);
      } else if (valID === "#archier") {
          val = $(e).html();
          $(".popover " + valID).val(val);
      } else if (valID === "#archier1") {
          val = $(e).html();
          $(".popover " + valID).val(val);
      } else if (valID === "#archier2") {
          val = $(e).html();
          $(".popover " + valID).val(val);
      } else if (valID === "#background") {
          val = $(e).css('background-color');
          var parts = val.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          
          $(".popover " + "#background").val(hexString);
      } else if (valID === "#img") {
          val = $(e).attr("src");
          var val2 = $(e).attr("width");
          var val3 = $(e).attr("height");
          var val4 = $(e).parent().attr("href");
          $(".popover " + valID).val(val);
          $(".popover " + "#img_width").val(val2);
          $(".popover " + "#img_height").val(val3);
          $(".popover " + "#link_img").val(val4);
          $(".popover " + "#blah").attr('src', val);
      } else if (valID === "#img2") {
          val = $(e).attr("src");
         $(".popover " + valID).val(val);
          $(".popover " + "#blah2").attr('src', val);
      } else if (valID === "#color_hr") {
          val = $(e).css("border-color");
          var parts = val.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();

          var val2 = $(e).css("width");
          var val3 = $(e).css("border-width");
          $(".popover " + "#color_hr").val(hexString);
          $(".popover " + "#width_hr").val(val2);
          $(".popover " + "#solid_hr").val(val3);
      } else if (valID === "#facebook") {
          val = $(e).parent().attr("href");
          var val2 = $(e).parent().css("color");
          var val3 = $(e).parent().css("font-size");
          $(".popover " + valID).val(val);
          var parts = val2.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          $(".popover " + "#color_facebook").val(hexString);
          $(".popover " + "#size_facebook").val(val3);

      } else if (valID === "#google") {
          val = $(e).parent().attr("href");
          var val2 = $(e).parent().css("color");
          var val3 = $(e).parent().css("font-size");
          $(".popover " + valID).val(val);
          var parts = val2.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          $(".popover " + "#color_google").val(hexString);
          $(".popover " + "#size_google").val(val3);

      } else if (valID === "#twitter") {
          val = $(e).parent().attr("href");
          var val2 = $(e).parent().css("color");
          var val3 = $(e).parent().css("font-size");
          $(".popover " + valID).val(val);
          var parts = val2.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          $(".popover " + "#color_twitter").val(hexString);
          $(".popover " + "#size_twitter").val(val3);

      } else if (valID === "#title2") {
          var val = $(e).html();
          var val2 = $(e).css('color');
          var val3 = $(e).css('font-size');
          var val4 = $(e).css('text-align');
          var val5 = $(e).css('font-weight');

          var parts = val2.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          $(".popover " + valID).val(val);
          $(".popover " + "#color_title").attr('value', hexString);
          $(".popover " + "#size_title").val(val3);
          $(".popover " + "#align_title").val(val4);
          $(".popover " + "#bold_title").val(val5);
      } else if (valID === "#option") {
          val = $.map($(e).find("option"), function (e, i) { return $(e).text() });
          val = val.join("\n")
          $(".popover " + valID).text(val);
          //fix
      } else if (valID === "#menu") {
          val = $(e).html();
          var val2 = $(e).attr('href');
          var val3 = $(e).css('color');
          var val4 = $(e).css('background');
          var val5 = $(e).css('font-weight');
          var val6 = $(e).parent().css('text-align');
          var parts = val3.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();

          var tmp = val4.split(" n");
          var parts2 = tmp[0].match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts2[0]);
          for (var i = 1; i <= 3; ++i) {
              parts2[i] = parseInt(parts2[i]).toString(16);
              if (parts2[i].length == 1) parts2[i] = '0' + parts2[i];
          }
          var hexString2 = '#' + parts2.join('').toUpperCase();
          $(".popover " + valID).val(val.trim());
          $(".popover " + "#link_menu").val(val2);
          $(".popover " + "#color_menu").val(hexString);
          $(".popover " + "#background_menu").val(hexString2);
          $(".popover " + "#bold_menu").val(val5);
          $(".popover " + "#align_menu").val(val6);
          //fix
      } else if (valID === "#link") {
          var links = $(e).html().split('<span style="margin-right:20px;"></span>');
          for (var i = 0; i + 1 < links.length; i++) {
              var tmp = links[i].split('>');
              var tmp2 = tmp[0].split('"');
              var tmp3 = tmp[1].split("<");
              $(".popover " + valID).append(tmp3[0] + "|" + tmp2[1]);
              if (i + 2 == links.length) { } else {
                  $(".popover " + valID).append("\n");
              }
          }
          var val2 = $(e).children().css('color');

          var parts = val2.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();
          $(".popover " + "#color_link").attr('value', hexString);
          var val3 = $(e).children().css('font-weight');
          $(".popover " + "#bold_link").val(val3);

          //fix
      } else if (valID === "#menu2") {
          val = $(e).html();
          var val2 = $(e).attr('href');
          var val3 = $(e).css('color');
          var val4 = $(e).css('background');
          var val5 = $(e).css('font-weight');
          var val6 = $(e).parent().css('text-align');
          var parts = val3.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts[0]);
          for (var i = 1; i <= 3; ++i) {
              parts[i] = parseInt(parts[i]).toString(16);
              if (parts[i].length == 1) parts[i] = '0' + parts[i];
          }
          var hexString = '#' + parts.join('').toUpperCase();

          var tmp = val4.split(" n");
          var parts2 = tmp[0].match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

          delete (parts2[0]);
          for (var i = 1; i <= 3; ++i) {
              parts2[i] = parseInt(parts2[i]).toString(16);
              if (parts2[i].length == 1) parts2[i] = '0' + parts2[i];
          }
          var hexString2 = '#' + parts2.join('').toUpperCase();
          $(".popover " + valID).val(val.trim());
          $(".popover " + "#link_menu2").val(val2);
          $(".popover " + "#color_menu2").val(hexString);
          $(".popover " + "#background_menu2").val(hexString2);
          $(".popover " + "#bold_menu2").val(val5);
          $(".popover " + "#align_menu2").val(val6);
          //fix
      } else if (valID === "#checkboxes") {
        val = $.map($(e).find("label"), function(e,i){return $(e).text().trim()});
        val = val.join("\n")
      $(".popover "+valID).text(val);
      } else if(valID==="#radios"){
        val = $.map($(e).find("label"), function(e,i){return $(e).text().trim()});
        val = val.join("\n")
      $(".popover "+valID).text(val);
      } else if(valID==="#inline-checkboxes"){
        val = $.map($(e).find("label"), function(e,i){return $(e).text().trim()});
        val = val.join("\n")
          $(".popover "+valID).text(val);
      } else if(valID==="#inline-radios"){
        val = $.map($(e).find("label"), function(e,i){return $(e).text().trim()});
        val = val.join("\n")
          $(".popover "+valID).text(val);
      } else if(valID==="#button") {
        val = $(e).text();
        var type = $(e).find("button").attr("class").split(" ").filter(function(e){return e.match(/btn-.*/)});
        $(".popover #color option").attr("selected", null);
        if(type.length === 0){
          $(".popover #color #default").attr("selected", "selected");
        } else {
          $(".popover #color #"+type[0]).attr("selected", "selected");
        }
        val = $(e).find(".btn").text();
        $(".popover #button").val(val);
      } else {
        val = $(e).text();
        $(".popover " + valID).val(val);
      }
    });

    $(".popover").delegate(".btn-danger", "click", function(e){
      e.preventDefault();
      $active_component.popover("hide");
    });

    $(".popover").delegate(".btn-info", "click", function(e){
      e.preventDefault();
      var inputs = $(".popover input");
      inputs.push($(".popover textarea")[0])
      console.log(inputs);
    $.each(inputs, function(i,e){
        var vartype = $(e).attr("id");
        // UI >> Code
      var value = $active_component.find('[data-valtype="'+vartype+'"]')
      if(vartype==="placeholder"){
        $(value).attr("placeholder", $(e).val());
      } else if (vartype === "checkbox") {
          if ($(e).is(":checked")) {
              $(value).attr("checked", true);
          }
          else {
              $(value).attr("checked", false);
          }
      } else if (vartype === "img") {
          $(value).attr("src", $(e).val());
          $(value).attr("width", $('#img_width').val());
          $(value).attr("height", $('#img_height').val());
          $(value).parent().attr("href", $('#link_img').val());
          $(value).attr("title", $('#img_width').val() + " x " + $('#img_height').val());

      } else if (vartype === "img2") {
          $(value).attr("src", $(e).val());
      } else if (vartype === "option") {
          var options = $(e).val().split("\n");
          $(value).html("");
          $.each(options, function (i, e) {
              $(value).append("\n     ");
              $(value).append($("<option>").text(e));
          });
          //fixarchier
      } else if (vartype === "background") {
          $(value).css('background-color', $('#background').val());

          //fix
      } else if (vartype === "menu") {
          $(value).html($(e).val());
          var tmp = $('#link_menu').val();
          var tmp1 = $('#color_menu').val();
          var tmp2 = $('#bold_menu').val();
          var tmp3 = $('#background_menu').val();
          var tmp4 = $('#align_menu').val();
          $(value).attr("href", tmp);
          $(value).css("color", tmp1);
          $(value).css("font-weight", tmp2);
          $(value).css("background", tmp3);
          $(value).parent().css("text-align", tmp4);

          //fix
      } else if (vartype === "menu2") {
          $(value).html($(e).val());

          var tmp = $('#link_menu2').val();
          var tmp1 = $('#color_menu2').val();
          var tmp2 = $('#bold_menu2').val();
          var tmp3 = $('#background_menu2').val();
          var tmp4 = $('#align_menu2').val();
          $(value).attr("href", tmp);
          $(value).css("color", tmp1);
          $(value).css("font-weight", tmp2);
          $(value).css("background", tmp3);
          $(value).parent().css("text-align", tmp4);

          //fix
      } else if (vartype === "archier") {
          var tmp = $('#archier').val();
          $(value).html(tmp);
          if ($('#archier1').val() != null) {
              $($active_component.find('[data-valtype="archier1"]')).html($('#archier1').val());
          }
          if ($('#archier2').val() != null) {
              $($active_component.find('[data-valtype="archier2"]')).html($('#archier2').val());
          }
          //fix
      } else if (vartype === "archier1") {
          var tmp = $('#archier1').val();
          $(value).html(tmp);
          var tmp2 = $('#archier2').val();
          var arch2 = $active_component.find('[data-valtype="archier2"]');
          $(arch2).html(tmp2);
          //fix
      } else if (vartype === "link") {
          var links = $(e).val().split("\n");
          var color = $("#color_link").val();
          var bold = $("#bold_link").val();
          if (!links[0]) { $(value).html(""); } else {
              $(value).html("");
              for (var i = 0; i < links.length; i++) {
                  var ops = links[i].split("|");
                  $(value).append("<a href=" + ops[1] + " style='color:" + color + ";font-weight:"+bold+";text-decoration:none;'>" + ops[0] + "</a><span style='margin-right:20px;'></span>");
              }
          }
      } else if (vartype === "title2") {
          $(value).html($(e).val());
          $(value).css('color', $('#color_title').val());
          $(value).css('font-size', $('#size_title').val());
          $(value).css('font-weight', $('#bold_title').val());
          $(value).css('text-align', $('#align_title').val());
          //fix
      } else if (vartype === "facebook") {
          if ($('#facebook').val() != "") {
              $(value).parent().removeAttr('hidden');
              $(value).parent().css('color', $('#color_facebook').val());
              $(value).parent().css('font-size', $('#size_facebook').val());
              $(value).parent().attr('href', $('#facebook').val());
          }
          else { $(value).parent().attr('hidden',''); }
          //fix
      } else if (vartype === "google") {
          if ($('#google').val() != "") {
              $(value).parent().css('visibility', 'visible');
              $(value).parent().css('color', $('#color_google').val());
              $(value).parent().css('font-size', $('#size_google').val());
              $(value).parent().attr('href', $('#google').val());
          }
          else { $(value).parent().css('visibility', 'hidden'); }
          //fix
      } else if (vartype === "twitter") {
          if ($('#twitter').val() != "") {
              $(value).parent().css('visibility', 'visible');
              $(value).parent().css('color', $('#color_twitter').val());
              $(value).parent().css('font-size', $('#size_twitter').val());
              $(value).parent().attr('href', $('#twitter').val());
          }
          else { $(value).parent().css('visibility', 'hidden'); }
          //fix
      } else if (vartype === "facebook") {
          if ($('#facebook').val() != "") {
              $(value).parent().css('visibility', 'visible');
              $(value).parent().css('color', $('#color_facebook').val());
              $(value).parent().css('font-size', $('#size_facebook').val());
              $(value).parent().attr('href', $('#facebook').val());
          }
          else { $(value).parent().css('visibility', 'hidden'); }
          //fix
      } else if (vartype === "checkboxes") {
        var checkboxes = $(e).val().split("\n");
        $(value).html("\n      <!-- Multiple Checkboxes -->");
        $.each(checkboxes, function(i,e){
          if(e.length > 0){
            $(value).append('\n      <label class="checkbox">\n        <input type="checkbox" value="'+e+'">\n        '+e+'\n      </label>');
          }
        });
        $(value).append("\n  ")
      } else if (vartype==="radios"){
        var radios = $(e).val().split("\n");
        $(value).html("\n      <!-- Multiple Radios -->");
        $.each(radios, function(i,e){
          if(e.length > 0){
            $(value).append('\n      <label class="radio">\n        <input type="radio" value="'+e+'">\n        '+e+'\n      </label>');
          }
        });
        $(value).append("\n  ")
          $($(value).find("input")[0]).attr("checked", true)
      } else if (vartype==="inline-checkboxes"){
        var checkboxes = $(e).val().split("\n");
        $(value).html("\n      <!-- Inline Checkboxes -->");
        $.each(checkboxes, function(i,e){
          if(e.length > 0){
            $(value).append('\n      <label class="checkbox inline">\n        <input type="checkbox" value="'+e+'">\n        '+e+'\n      </label>');
          }
        });
        $(value).append("\n  ")
      } else if (vartype==="inline-radios"){
        var radios = $(e).val().split("\n");
        $(value).html("\n      <!-- Inline Radios -->");
        $.each(radios, function(i,e){
          if(e.length > 0){
            $(value).append('\n      <label class="radio inline">\n        <input type="radio" value="'+e+'">\n        '+e+'\n      </label>');
          }
        });
        $(value).append("\n  ")
          $($(value).find("input")[0]).attr("checked", true)
      } else if (vartype === "button"){
        var type =  $(".popover #color option:selected").attr("id");
        $(value).find("button").text($(e).val()).attr("class", "btn "+type);
      } else {
        $(value).text($(e).val());
      }
    $active_component.popover("hide");
    genSource();
    });
    });
  });
  $("#navtab").delegate("#sourcetab", "click", function(e){
    genSource();
  });
});
